#include "XmlOStream.h"

int level;

xml::XmlOStream::XmlOStream( const char * filename)
{
	active = true;
	if((outputFile = std::fopen(filename, "w")) == NULL)
	{
		std::cerr<<"Cannot open file "<<filename<< " for writing...\n";
		active = false;		
	}	
}

xml::XmlOStream::~XmlOStream( void )
{
	fclose(outputFile);
}

xml::XmlOStream xml::XmlOStream::operator<<( XmlData & data)
{	
	srand(time(0));
	if(!active)
		return (*this);

	xml::XmlNode *root = data.getRoot();
	level = 0;
	writeXmlNode(root);	
	return (*this);
}

void xml::XmlOStream::writeXmlNode( XmlNode *node )
{
	int size = node->children.size();
	char *content = NULL, *tag = NULL;

	for(int i=0; i<level; ++i)
		std::fprintf(outputFile, "\t");
	
	if(node->tag.size() > 0)
		std::fprintf(outputFile, "<%s>", node->tag[0]);
	else
		std::fprintf(outputFile, "<>");


	if(node->children.size() == 0)
	{
		if(node->content.size() > 0 && node->content[0] != 0)
			std::fprintf(outputFile, "%s", node->content[0]);
		else
			std::fprintf(outputFile, "%g", (rand()%10000)/10000.0);
	}
	

	if(node->children.size() > 0)
		std::fprintf(outputFile, "\n");

	for(unsigned int i=0; i<node->children.size(); ++i)
	{
		level++;
		writeXmlNode(node->children[i]);
		level--;
	}

	if(node->children.size() > 0)
		for(int i=0; i<level; ++i)
			std::fprintf(outputFile, "\t");

	if(node->tag.size() > 0)
		std::fprintf(outputFile, "</%s>\n", node->tag[0]);	
	else
		std::fprintf(outputFile, "</>\n");
}


